package com.eastmoney.myapplication

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Intent
import android.net.VpnService
import android.os.ParcelFileDescriptor
import androidx.core.app.NotificationCompat

class GoVpnService : VpnService() {

    private var vpnInterface: ParcelFileDescriptor? = null
    private var isRunning = false
    private val NOTIFICATION_ID = 1
    private val CHANNEL_ID = "GoVpnService"

    override fun onCreate() {
        super.onCreate()
        createNotificationChannel()
    }

    @SuppressLint("ForegroundServiceType")
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        println("onStartCommand33")

        val notification: Notification = createNotification() // 构造通知
        startForeground(1, notification) // 不需要带类型

        // 在新线程中启动VPN
        Thread {
            try {
                println("onStartCommand")
                startVpn()
            } catch (e: Exception) {
                e.printStackTrace()
                stopSelf() // 发生错误时停止服务
            }
        }.start()

        return START_STICKY
    }

    private fun createNotificationChannel() {
        val channel = NotificationChannel(
            CHANNEL_ID,
            "GoVPN Service",
            NotificationManager.IMPORTANCE_LOW
        ).apply {
            description = "GoVPN Service Channel"
        }
        val notificationManager = getSystemService(NotificationManager::class.java)
        notificationManager.createNotificationChannel(channel)
    }

    private fun createNotification(): Notification {
        val notificationIntent = Intent(this, GoVpnService::class.java)
        val pendingIntent = PendingIntent.getActivity(
            this,
            0,
            notificationIntent,
            PendingIntent.FLAG_IMMUTABLE
        )

        val builder = NotificationCompat.Builder(this, CHANNEL_ID)

        return builder
            .setContentTitle("GoVPN Service")
            .setContentText("VPN is running")
            .setSmallIcon(android.R.drawable.ic_lock_lock)
            .setContentIntent(pendingIntent)
            .build()
    }

        private fun startVpn() {

        println("1 startVpn")
        if (isRunning) return
        isRunning = true
        println("2 startVpn")
        try {
            // 配置并创建 VPN 接口
            val builder = Builder()
                .setSession("GoVPN")
                .addAddress("10.0.0.2", 24)
                .addDnsServer("8.8.8.8")
                .addRoute("10.10.10.0", 0)
                .setMtu(1500)

            // 建立 VPN 接口
            vpnInterface = builder.establish()

            if (vpnInterface == null) {
                throw Exception("Failed to establish VPN interface")
            }

            // 获取文件描述符
            val fd = vpnInterface?.fileDescriptor ?: return

            println("创建tun")
        } catch (e: Exception) {
            e.printStackTrace()
            isRunning = false
        }
    }

    override fun onDestroy() {
        isRunning = false
        vpnInterface?.close()
        super.onDestroy()
    }
}